# -*- coding:utf-8 -*-

from flask import render_template, request, jsonify, current_app
from . import other
from app import db
from app.models.business import Business
from app.tools.log import log
from app.tools.permission import permission
from app.tools.safe import safe_data
from flask_login import login_required
import os
from app.tools.picture import qiniu_delete, delete_after_days


@other.before_request
@login_required
@permission(['upload', 'admin', 'super'])
def check_permission():
	return

@other.route('/<btype>/')
def other_list(btype):	#返回业务的展示页面，具体的业务数据由ajax异步获取
	titles = {'rent': u'租赁业务', 'finance': u'金融业务', 'service': u'服务'}
	if btype not in titles.keys():
		return render_template('404.html'), 404
	
	return render_template('business/other_base.html', btype=btype, title=titles[btype])

@other.route('/get_list/')
def get_list():	#获取业务信息
	limit = int(request.values.get('limit', '10'))
	offset = int(request.values.get('offset', '0'))
	btype = request.values.get('btype')
	if btype is None:
		return jsonify({'state': -1, 'msg': u'参数不全'})
	if btype not in ['rent', 'finance', 'service']:
		return jsonify({'state': 1, 'msg': u'参数错误'})
	result = Business.query.filter_by(bs_type=btype).order_by(Business.order).paginate(offset/limit+1, limit, False)
	count = result.total
	data = []
	domain = current_app.config['QINIU_DOMAIN']
	for item in result.items:
		data.append({
			'order': item.order,
			'name': item.name,
			'picture': domain + item.picture + '?imageView2/1/w/300/h/200',
			'info': item.info,
			'details': item.details,
			'bid': item.id,
			'origin': item.order,
		})
	json = {'total': count, 'rows': data}
	return jsonify(json)
	
@other.route('/add/', methods=["GET", "POST"])
def add():	#添加业务
	values = request.values
	data = {}
	btype = values.get('btype')	#业务类型
	if btype is None:
		return jsonify({'state': -1, 'msg': u'参数不全'})
	if btype not in ['rent', 'finance', 'service']:
		return jsonify({'state': 1, 'msg': u'参数错误'})
	data['name'] = values.get('name')
	data['info'] = values.get('info')
	data['details'] = values.get('details')	
	data['picture'] = values.get('pic')
	for item in data.values():
		if item is None or item == '':
			return jsonify({'state': -1, 'msg': u'内容不能为空'})
	result = Business.query.filter_by(bs_type=btype).order_by(Business.order.desc()).first()
	data['order'] = result.order + 1 if result else 1
	data['bs_type'] = btype
	data = safe_data(data)
	bs = Business(**data)
	bs.save()
	delete_after_days.delay(data['picture'], 0)	
	log(u"上传物料%s"%data['name'])
	return jsonify({'state': 0})

@other.route('/edit/', methods=["GET", "POST"])
def edit():	#编辑业务
	values = request.values
	data = {}
	bid = values.get('bid')	#原业务的id
	result = Business.query.filter_by(id=bid).first()
	if not result:
		return jsonify({'state': 2, 'msg': u'对象不存在'})
	data['name'] = values.get('name')
	data['info'] = values.get('info')
	data['details'] = values.get('details')
	for item in data.values():
		if item is None or item == '':
			return jsonify({'state': -1, 'msg': u'内容不能为空'})
	if values.get('pic') != '':
		old_pic = result.picture
		result.picture = values.get('pic')
	data = safe_data(data)
	result.name = data['name']
	result.info = data['info']
	result.details = data['details']
	result.save()
	if values.get('pic') != '':
		qiniu_delete.delay(old_pic)
		delete_after_days.delay(result.picture, 0)
	log(u"修改物料%s"%data['name'])
	return jsonify({'state': 0})

@other.route('/delete/', methods=["GET", "POST"])
def delete():	#删除业务
	values = request.values
	data = {}
	bid = values.get('bid')
	result = Business.query.filter_by(id=bid).first()
	if not result:
		return jsonify({'state': 2, 'msg': u'对象不存在'})
	name = result.name
	order = result.order
	items = Business.query.filter(Business.order > order).all()
	for item in items:
		item.order = item.order - 1
		db.session.add(item)
	old_pic = result.picture
	result.delete()
	qiniu_delete.delay(old_pic)
	log(u"删除物料%s" % name)
	return jsonify({'state': 0})

@other.route('/reorder/', methods=["GET", "POST"])
def reorder():	#业务排序
	btype = request.values.get('btype')
	if btype is None:
		return jsonify({'state': -1, 'msg': u'参数不全'})
	if btype not in ['rent', 'finance', 'service']:
		return jsonify({'state': 1, 'msg': u'参数错误'})
	table = request.values.get('table')
	if table is None:
		return jsonify({'state': -1, 'msg': u'参数不足'})
	rows = table.split(';')
	for row in rows:
		if not row:
			break
		items = row.split(',')
		bid = int(items[0].split('=')[-1])
		order = int(items[1].split('=')[-1])
		index = int(items[2].split('=')[-1])
		if order != index + 1:
			result = Business.query.filter_by(bs_type=btype, id=bid).first()
			if result:
				result.order = index + 1
				result.save()
				log(u"调整物料%s顺序"%result.name)
	return jsonify({'state': 0})
